package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.management.aop.anno.RedisAnno;
import com.qk.vo.PortalVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class RedisAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    // private static final String CACHE_PORTAL_KEY_PREFIX = "qk:portal:";

    @Pointcut("@annotation(com.qk.management.aop.anno.RedisAnno)")
    public void pt() {
    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = null;
        String redisKey = null;
        long expire = 0;
        TimeUnit expireTimeUnit = null;
        try {
            String name = pjp.getSignature().getName();
            Class<?> targetClass = pjp.getTarget().getClass();
            Method method = targetClass.getMethod(name);
            RedisAnno redisAnno = method.getAnnotation(RedisAnno.class);
            redisKey = redisAnno.keyPrefix() + name;
            expire = redisAnno.expire();
            expireTimeUnit = redisAnno.expireTimeUnit();
            String jsonStr = redisTemplate.opsForValue().get(redisKey);
            //判断缓存命中
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                return JSONUtil.toBean(jsonStr, method.getReturnType());
            }
        } catch (Exception e) {
            log.error("查询缓存异常{}", e.getMessage());
        }

        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            CommonException.throwCommonException(ParamEnum.OPERATE_ERROR);
            log.error("操作失败:{}", e.getMessage());
        }

        try {
            String json = JSONUtil.toJsonStr(proceed);
            redisTemplate.opsForValue().set(redisKey, json, expire, expireTimeUnit);
        } catch (Exception e) {
            log.error("添加缓存异常{}", e.getMessage());
        }
        return proceed;
    }
}
